import {
	API_CONFIG,
	PROMPT_TEMPLATES,
	ERROR_MESSAGES
} from '../config/api.config.js'

// 缓存管理
const cache = {
	// 健康分析缓存
	healthAnalysis: new Map(),
	// 建议缓存
	advice: new Map(),

	// 生成缓存键
	generateKey(healthData) {
		return JSON.stringify({
			age: healthData.age,
			gender: healthData.gender,
			height: healthData.height,
			weight: healthData.weight,
			bmi: healthData.bmi,
			bloodPressure: healthData.bloodPressure,
			bloodPressureStatus: healthData.bloodPressureStatus,
			exercise: healthData.exercise,
			sleep: healthData.sleep,
			smoke: healthData.smoke,
			symptoms: healthData.symptoms
		})
	},

	// 获取缓存
	get(type, key) {
		const cacheMap = this[type]
		if (cacheMap && cacheMap.has(key)) {
			const cached = cacheMap.get(key)
			// 检查缓存是否过期（24小时）
			if (Date.now() - cached.timestamp < 24 * 60 * 60 * 1000) {
				console.log(`使用缓存数据: ${type}`)
				return cached.data
			} else {
				// 缓存过期，删除
				cacheMap.delete(key)
			}
		}
		return null
	},

	// 设置缓存
	set(type, key, data) {
		const cacheMap = this[type]
		if (cacheMap) {
			cacheMap.set(key, {
				data: data,
				timestamp: Date.now()
			})
			console.log(`缓存数据: ${type}`)
		}
	},

	// 清除缓存
	clear(type) {
		if (type) {
			this[type].clear()
		} else {
			this.healthAnalysis.clear()
			this.advice.clear()
		}
		console.log('缓存已清除')
	}
}

// API服务配置
const API_BASE_URL = 'http://127.0.0.1:3000' // 假设您的Express服务器运行在3000端口

// 健康分析API服务
export const healthAPI = {
	// 调用AI进行健康分析
	async analyzeHealth(healthData) {
		try {
			// 检查缓存
			const cacheKey = cache.generateKey(healthData)
			const cachedResult = cache.get('healthAnalysis', cacheKey)
			if (cachedResult) {
				return cachedResult
			}

			const prompt = PROMPT_TEMPLATES.HEALTH_ANALYSIS(healthData)

			const response = await this.makeRequest({
				url: `${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.CHAT}`,
				data: {
					message: prompt
				}
			})

			const result = {
				success: true,
				content: response.content
			}

			// 缓存结果
			cache.set('healthAnalysis', cacheKey, result)

			return result
		} catch (error) {
			console.error('AI分析请求失败:', error)
			return {
				success: false,
				error: error.message || ERROR_MESSAGES.UNKNOWN_ERROR
			}
		}
	},

	// 获取个性化健康建议
	async getPersonalizedAdvice(healthData) {
		try {
			// 检查缓存
			const cacheKey = cache.generateKey(healthData)
			const cachedResult = cache.get('advice', cacheKey)
			if (cachedResult) {
				return cachedResult
			}

			const prompt = PROMPT_TEMPLATES.PERSONALIZED_ADVICE(healthData)

			const response = await this.makeRequest({
				url: `${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.CHAT}`,
				data: {
					message: prompt
				}
			})

			const result = {
				success: true,
				content: response.content
			}

			// 缓存结果
			cache.set('advice', cacheKey, result)

			return result
		} catch (error) {
			console.error('获取建议请求失败:', error)
			return {
				success: false,
				error: error.message || ERROR_MESSAGES.UNKNOWN_ERROR
			}
		}
	},

	// 通用请求方法
	async makeRequest(options) {
		try {
			console.log('正在请求API:', options.url)

			const response = await uni.request({
				url: options.url,
				method: 'POST',
				data: options.data,
				header: API_CONFIG.HEADERS
			})

			console.log('API响应:', response)

			if (response.statusCode === 200) {
				if (response.data.status === 0) {
					return response.data
				} else {
					// Ollama服务错误
					throw new Error(response.data.content || ERROR_MESSAGES.OLLAMA_ERROR)
				}
			} else {
				throw new Error(`HTTP ${response.statusCode}: ${ERROR_MESSAGES.API_ERROR}`)
			}
		} catch (error) {
			console.error('API请求失败:', error)
			throw error
		}
	},

	// 清除缓存
	clearCache(type) {
		cache.clear(type)
	}
}

// 解析AI返回的文本内容
export const parseAIResponse = {
	// 解析健康分析结果
	parseHealthAnalysis(content) {
		try {
			console.log('解析AI健康分析结果:', content)
			// 过滤掉思考过程
			const cleanContent = this.filterThinkingProcess(content)
			console.log('过滤后的内容:', cleanContent)

			// 提取健康评分
			const scoreMatch = cleanContent.match(/健康评分[：:][^\d]*(\d+)/)
			const healthScore = scoreMatch ? parseInt(scoreMatch[1]) : 75

			// 提取评分说明
			const scoreDescMatch = cleanContent.match(/评分说明[：:]\s*([^\n]+)/)
			const scoreDescription = scoreDescMatch ? scoreDescMatch[1].trim() : ''

			// 提取BMI分析
			const bmiMatch = cleanContent.match(/BMI分析[：:]\s*([^\n]+)/)
			const bmiAnalysis = bmiMatch ? bmiMatch[1].trim() : ''

			// 提取血压分析
			const bpMatch = cleanContent.match(/血压分析[：:]\s*([^\n]+)/)
			const bpAnalysis = bpMatch ? bpMatch[1].trim() : ''

			// 提取生活习惯分析
			const lifestyleMatch = cleanContent.match(/生活习惯评估[：:]\s*([^\n]+)/)
			const lifestyleAnalysis = lifestyleMatch ? lifestyleMatch[1].trim() : ''

			// 提取主要健康风险点
			const riskMatch = cleanContent.match(/主要健康风险点[：:]\s*([^\n]+)/)
			const healthRisks = riskMatch ? riskMatch[1].trim() : ''

			// 提取改善建议（支持多行）
			const improveMatch = cleanContent.match(/改善建议[：:]\s*([\s\S]*)/)
			const improvementAdvice = improveMatch ? improveMatch[1].trim() : ''

			const result = {
				healthScore,
				scoreDescription,
				bmiAnalysis,
				bpAnalysis,
				lifestyleAnalysis,
				healthRisks,
				improvementAdvice,
				fullContent: cleanContent
			}
			console.log('解析结果:', result)
			return result
		} catch (error) {
			console.error('解析AI响应失败:', error)
			return {
				healthScore: 75,
				scoreDescription: '分析数据中...',
				bmiAnalysis: '分析数据中...',
				bpAnalysis: '分析数据中...',
				lifestyleAnalysis: '分析数据中...',
				healthRisks: '分析数据中...',
				improvementAdvice: '分析数据中...',
				fullContent: content
			}
		}
	},

	// 解析个性化建议
	parseAdvice(content) {
		try {
			console.log('解析AI建议结果:', content)

			// 过滤掉思考过程
			const cleanContent = this.filterThinkingProcess(content)
			const advice = []

			// 提取饮食建议
			const dietMatch = cleanContent.match(/饮食建议[：:]([\s\S]*?)(?=\n|运动建议|$)/)
			if (dietMatch) {
				advice.push({
					icon: '🥗',
					title: '饮食建议',
					content: dietMatch[1].trim(),
					description: dietMatch[1].trim(),
					tags: ['饮食', '营养', '健康']
				})
			}

			// 提取运动建议
			const exerciseMatch = cleanContent.match(/运动建议[：:]([\s\S]*?)(?=\n|生活方式|$)/)
			if (exerciseMatch) {
				advice.push({
					icon: '🏃‍♂️',
					title: '运动建议',
					content: exerciseMatch[1].trim(),
					description: exerciseMatch[1].trim(),
					tags: ['运动', '健身', '健康']
				})
			}

			// 提取生活方式建议
			const lifestyleMatch = cleanContent.match(/生活方式改善建议[：:]([\s\S]*?)(?=\n|需要关注|$)/)
			if (lifestyleMatch) {
				advice.push({
					icon: '💡',
					title: '生活方式建议',
					content: lifestyleMatch[1].trim(),
					description: lifestyleMatch[1].trim(),
					tags: ['生活', '习惯', '改善']
				})
			}

			// 提取需要关注的健康指标
			const focusMatch = cleanContent.match(/需要重点关注的健康指标[：:]([\s\S]*?)(?=\n|预防性|$)/)
			if (focusMatch) {
				advice.push({
					icon: '📊',
					title: '重点关注指标',
					content: focusMatch[1].trim(),
					description: focusMatch[1].trim(),
					tags: ['监测', '健康', '指标']
				})
			}

			// 提取预防性建议
			const preventMatch = cleanContent.match(/预防性建议[：:]([\s\S]*?)(?=\n|$)/)
			if (preventMatch) {
				advice.push({
					icon: '🛡️',
					title: '预防性建议',
					content: preventMatch[1].trim(),
					description: preventMatch[1].trim(),
					tags: ['预防', '健康', '保护']
				})
			}

			// 如果没有解析到具体建议，返回原始内容
			if (advice.length === 0) {
				advice.push({
					icon: '💡',
					title: 'AI建议',
					content: cleanContent,
					description: cleanContent,
					tags: ['健康', '建议']
				})
			}

			console.log('解析的建议:', advice)
			return advice
		} catch (error) {
			console.error('解析建议失败:', error)
			return [{
				icon: '💡',
				title: 'AI建议',
				content: content,
				description: content,
				tags: ['健康', '建议']
			}]
		}
	},

	// 过滤思考过程
	filterThinkingProcess(content) {
		// 移除 <think> 标签及其内容
		let cleanContent = content.replace(/<think>[\s\S]*?<\/think>/g, '')

		// 移除其他可能的思考过程标记
		cleanContent = cleanContent.replace(/###\s*结论[：:]/g, '')
		cleanContent = cleanContent.replace(/###\s*总结建议[：:]/g, '')

		// 移除多余的空行和格式
		cleanContent = cleanContent.replace(/\n\s*\n\s*\n/g, '\n\n')
		cleanContent = cleanContent.trim()

		// 移除开头的多余空行
		cleanContent = cleanContent.replace(/^\n+/, '')

		// 移除结尾的多余空行
		cleanContent = cleanContent.replace(/\n+$/, '')

		console.log('过滤思考过程后的内容:', cleanContent)
		return cleanContent
	}
}

// 后端接口配置
const BASE_URL = 'http://127.0.0.1:3000'; 

// 统一的请求处理函数
const makeRequest = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {
				resolve(res.data);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};

// 收藏相关接口
export const favoritesAPI = {
	// 获取收藏列表
	async getFavorites(userId) {
		try {
			const data = await makeRequest({
				url: `${BASE_URL}/api/favorites/list`,
				method: 'GET',
				data: {
					userId
				}
			});
			return data;
		} catch (error) {
			console.error('获取收藏失败:', error);
			return [];
		}
	},

	// 添加收藏
	async addFavorite(userId, {
		title,
		content,
		tags
	}) {
		try {
			console.log('添加收藏:', {
				userId,
				title,
				content,
				tags
			})
			// 确保参数不包含undefined值
			const safeTitle = title || '';
			const safeContent = content || '';
			const safeTags = Array.isArray(tags) ? tags.filter(tag => tag !== undefined).join(',') : '';

			const data = await makeRequest({
				url: `${BASE_URL}/api/favorites/add`,
				method: 'POST',
				data: {
					userId,
					title: safeTitle,
					content: safeContent,
					tags: safeTags
				}
			});
			return data;
		} catch (error) {
			console.error('添加收藏失败:', error);
			return {
				success: false,
				error: error.message
			};
		}
	},

	// 删除收藏
	async deleteFavorite(userId, id) {
		try {
			const data = await makeRequest({
				url: `${BASE_URL}/api/favorites/delete`,
				method: 'POST',
				data: {
					userId,
					id
				}
			});
			return data;
		} catch (error) {
			console.error('删除收藏失败:', error);
			return {
				success: false,
				error: error.message
			};
		}
	}
};

// 健康提醒相关接口
export const remindersAPI = {
	// 获取提醒列表
	async getReminders(userId) {
		try {
			const data = await makeRequest({
				url: `${BASE_URL}/api/reminders/list`,
				method: 'GET',
				data: {
					userId
				}
			});
			return data;
		} catch (error) {
			console.error('获取提醒失败:', error);
			return [];
		}
	},

	// 添加提醒
	async addReminder(userId, {
		time,
		title,
		description,
		notified
	}) {
		try {
			// 确保参数不包含undefined值
			const safeTime = time || '';
			const safeTitle = title || '';
			const safeDescription = description || '';
			const safeNotified = notified ? 1 : 0;

			const data = await makeRequest({
				url: `${BASE_URL}/api/reminders/add`,
				method: 'POST',
				data: {
					userId,
					time: safeTime,
					title: safeTitle,
					description: safeDescription,
					notified: safeNotified
				}
			});
			return data;
		} catch (error) {
			console.error('添加提醒失败:', error);
			return {
				success: false,
				error: error.message
			};
		}
	},

	// 删除提醒
	async deleteReminder(userId, id) {
		try {
			const data = await makeRequest({
				url: `${BASE_URL}/api/reminders/delete`,
				method: 'POST',
				data: {
					userId,
					id
				}
			});
			return data;
		} catch (error) {
			console.error('删除提醒失败:', error);
			return {
				success: false,
				error: error.message
			};
		}
	}
};

// 分析结果相关接口
export const analysisAPI = {
	// 获取最新分析结果
	async getAnalysis(userId) {
		try {
			const data = await makeRequest({
				url: `${BASE_URL}/api/analysis/get`,
				method: 'GET',
				data: {
					userId
				}
			});
			return data;
		} catch (error) {
			console.error('获取分析结果失败:', error);
			return null;
		}
	},

	// 保存分析结果
	async saveAnalysis(userId, {
		healthData,
		healthScore,
		aiAnalysis,
		aiAdvice
	}) {
		try {
			console.log('保存分析结果到云端:', {
				userId,
				healthScore
			})

			// 确保参数不包含undefined值
			const safeHealthData = healthData || {};
			const safeHealthScore = healthScore || 0;
			const safeAiAnalysis = aiAnalysis || {};
			const safeAiAdvice = aiAdvice || [];

			const data = await makeRequest({
				url: `${BASE_URL}/api/analysis/save`,
				method: 'POST',
				data: {
					userId,
					healthData: JSON.stringify(safeHealthData),
					healthScore: safeHealthScore,
					aiAnalysis: JSON.stringify(safeAiAnalysis),
					aiAdvice: JSON.stringify(safeAiAdvice),
					overwrite: true, // 明确告诉后端这是覆盖操作
					timestamp: new Date().toISOString() // 添加时间戳
				}
			});

			console.log('保存分析结果响应:', data)
			return data;
		} catch (error) {
			console.error('保存分析结果失败:', error);
			return {
				success: false,
				error: error.message
			};
		}
	}
};